/*****************************************************************************
 * Java Plug-in Framework (JPF)
 * Copyright (C) 2004-2007 Dmitry Olshansky
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *****************************************************************************/
package fr.umlv.main;
	
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Locale;

import org.apache.commons.logging.LogFactory;
import org.java.plugin.PluginManager;
import org.java.plugin.util.ExtendedProperties;
import org.java.plugin.util.IoUtil;
import org.java.plugin.util.ResourceManager;


// TODO: Auto-generated Javadoc
/**
 * The Class Boot.
 */
public final class Boot {
    
    /** The Constant BOOT_ERROR_FILE_NAME. */
    public static final String BOOT_ERROR_FILE_NAME = "jpf-boot-error.txt"; //$NON-NLS-1$
    
    /** The Constant PROP_BOOT_CONFIG. */
    public static final String PROP_BOOT_CONFIG = "jpf.boot.config"; //$NON-NLS-1$
    
    /** The Constant PROP_BOOT_MODE. */
    public static final String PROP_BOOT_MODE = "jpf.boot.mode"; //$NON-NLS-1$
    
    /** The Constant BOOT_MODE_SHELL. */
    public static final String BOOT_MODE_SHELL = "shell"; //$NON-NLS-1$
    
    /** The Constant BOOT_MODE_START. */
    public static final String BOOT_MODE_START = "start"; //$NON-NLS-1$
    
    /** The Constant BOOT_MODE_STOP. */
    public static final String BOOT_MODE_STOP = "stop"; //$NON-NLS-1$
    
    /** The Constant BOOT_MODE_RESTART. */
    public static final String BOOT_MODE_RESTART = "restart"; //$NON-NLS-1$
    
    /** The Constant BOOT_MODE_LOAD. */
    public static final String BOOT_MODE_LOAD = "load"; //$NON-NLS-1$
    
    // This is for ResourceManager to look up resources.
    /** The Constant PACKAGE_NAME. */
    static final String PACKAGE_NAME = "org.java.plugin.boot"; //$NON-NLS-1$
    
    // Application bootstrap configuration parameter names goes here
    /** The Constant PARAM_CONTROL_HOST. */
    private static final String PARAM_CONTROL_HOST =
        "org.java.plugin.boot.controlHost"; //$NON-NLS-1$
    
    /** The Constant PARAM_CONTROL_PORT. */
    private static final String PARAM_CONTROL_PORT =
        "org.java.plugin.boot.controlPort"; //$NON-NLS-1$
    
    /** The Constant PARAM_ERROR_HANDLER. */
    private static final String PARAM_ERROR_HANDLER =
        "org.java.plugin.boot.errorHandler"; //$NON-NLS-1$
    
    /** The Constant PARAM_APP_INITIALIZER. */
    private static final String PARAM_APP_INITIALIZER =
        "org.java.plugin.boot.appInitializer"; //$NON-NLS-1$
    
    /**
     * The main method.
     *
     * @param args the arguments
     */
    public static void main(final String[] args) {
    	
        clearBootLog();
        // Load start-up configuration
        ExtendedProperties props = new ExtendedProperties(
                System.getProperties());
        try {
            InputStream strm = lookupConfig();
            try {
                props.load(strm);
            } finally {
                strm.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        String mode = props.getProperty(PROP_BOOT_MODE);
        if (mode != null) {
            mode = mode.trim().toLowerCase(Locale.ENGLISH);
        } else {
            // set SHELL mode by default
            mode = BOOT_MODE_SHELL;
        }
        props.setProperty(PROP_BOOT_MODE, mode);
        // Make sure that boot mode is always available as System property:
        System.setProperty(PROP_BOOT_MODE, mode);
        boolean useControlService = props.containsKey(PARAM_CONTROL_HOST)
            && props.containsKey(PARAM_CONTROL_PORT);
        BootErrorHandler errorHandler = getErrorHandlerInstance(
                props.getProperty(PARAM_ERROR_HANDLER), useControlService);
        try {
            if (props.getProperty("applicationRoot") == null) { //$NON-NLS-1$
                // Publish current folder as configuration parameter
                // to get it available as ${applicationRoot} variable
                // in extended properties syntax.
                String applicationRoot = new File(".").getCanonicalPath(); //$NON-NLS-1$
                props.put("applicationRoot", applicationRoot);  //$NON-NLS-1$
            }
            boot(props, useControlService, mode, errorHandler, args);
        } catch (Throwable t) {
            bootLog(t);
            errorHandler.handleFatalError(ResourceManager.getMessage(
                    Boot.PACKAGE_NAME, "bootFailed"), t); //$NON-NLS-1$
            System.exit(1);
        }
    }
    
    /**
     * Boot.
     *
     * @param config the config
     * @param useControlService the use control service
     * @param mode the mode
     * @param errorHandler the error handler
     * @param args the args
     * @return the application
     * @throws Exception the exception
     */
    public static Application boot(final ExtendedProperties config,
            final boolean useControlService, final String mode,
            final BootErrorHandler errorHandler, final String[] args)
            throws Exception {
        InetAddress controlHost = useControlService ? InetAddress.getByName(
                config.getProperty(PARAM_CONTROL_HOST)) : null;
        int controlPort = useControlService ? Integer.parseInt(
                config.getProperty(PARAM_CONTROL_PORT), 10) : 0;
        // handle given command
        if (useControlService && BOOT_MODE_STOP.equals(mode)) {
            if (!ControlThread.stopRunningApplication(controlHost,
                    controlPort)) {
            } else {
            }
            return null;
        }
        if (useControlService && BOOT_MODE_START.equals(mode)) {
            if (ControlThread.isApplicationRunning(controlHost,
                    controlPort)) {
                errorHandler.handleFatalError(
                        "Application already running."); //$NON-NLS-1$
                return null;
            }
            Application application =
                initApplication(errorHandler, config, args);
            if (!(application instanceof ServiceApplication)) {
                errorHandler.handleFatalError(
                        "Application is not a service."); //$NON-NLS-1$
                return null;
            }
            ControlThread controlThread = new ControlThread(controlHost,
                    controlPort, (ServiceApplication) application);
            application.startApplication();
            controlThread.start();
            return application;
        }
        if (useControlService && BOOT_MODE_RESTART.equals(mode)) {
            if (ControlThread.stopRunningApplication(controlHost,
                    controlPort)) {
            }
            Application application =
                initApplication(errorHandler, config, args);
            if (!(application instanceof ServiceApplication)) {
                errorHandler.handleFatalError(
                        "Application is not a service."); //$NON-NLS-1$
                return null;
            }
            ControlThread controlThread = new ControlThread(controlHost,
                    controlPort, (ServiceApplication) application);
            application.startApplication();
            controlThread.start();
            return application;
        }
        // SHELL or LOAD or an unknown modes
        if (useControlService
                && ControlThread.stopRunningApplication(controlHost,
                        controlPort)) {
        }

        Application application =
            initApplication(errorHandler, config, args);
        if (!BOOT_MODE_LOAD.equals(mode)) {
            application.startApplication();
            if ((application instanceof ServiceApplication)
                    && BOOT_MODE_SHELL.equals(mode)) {
                runShell();
                stopApplication(application);
            }
        }
        return application;
    }
    
    /**
     * Stop application.
     *
     * @param application the application
     * @throws Exception the exception
     */
    public static void stopApplication(final Application application)
            throws Exception {
        if (application instanceof ServiceApplication) {
            ((ServiceApplication) application).stopApplication();
        }
        PluginManager pluginManager = PluginManager.lookup(application);
        if (pluginManager != null) {
            pluginManager.shutdown();
        }
        LogFactory.getLog(Boot.class).info("logging system finalized"); //$NON-NLS-1$
        LogFactory.getLog(Boot.class).info("---------------------------------"); //$NON-NLS-1$
        LogFactory.releaseAll();
    }
    
    /**
     * Lookup config.
     *
     * @return the input stream
     * @throws IOException Signals that an I/O exception has occurred.
     */
    private static InputStream lookupConfig() throws IOException {
        String property = System.getProperty(PROP_BOOT_CONFIG);
        if (property != null) {
            return IoUtil.getResourceInputStream(str2url(property));
        }
        File file = new File("boot.properties"); //$NON-NLS-1$
        if (file.isFile()) {
            return new FileInputStream(file);
        }
        URL url = Boot.class.getClassLoader().getResource("boot.properties"); //$NON-NLS-1$
        if (url != null) {
            return IoUtil.getResourceInputStream(url);
        }
        url = Boot.class.getResource("boot.properties"); //$NON-NLS-1$
        if (url != null) {
            return IoUtil.getResourceInputStream(url);
        }
        throw new IOException("configuration file boot.properties not found"); //$NON-NLS-1$
    }
    
    /**
     * Str2url.
     *
     * @param str the str
     * @return the uRL
     * @throws MalformedURLException the malformed url exception
     */
    private static URL str2url(final String str) throws MalformedURLException {
        int p = str.indexOf("!/"); //$NON-NLS-1$
        if (p == -1) {
            try {
                return new URL(str);
            } catch (MalformedURLException mue) {
                return IoUtil.file2url(new File(str));
            }
        }
        if (str.startsWith("jar:")) { //$NON-NLS-1$
            return new URL(str);
        }
        File file = new File(str.substring(0, p));
        if (file.isFile()) {
            return new URL("jar:" + IoUtil.file2url(file) + str.substring(p)); //$NON-NLS-1$
        }
        return new URL("jar:" + str); //$NON-NLS-1$
    }

    /**
     * Gets the error handler instance.
     *
     * @param handler the handler
     * @param isServiceApp the is service app
     * @return the error handler instance
     */
    private static BootErrorHandler getErrorHandlerInstance(
            final String handler, final boolean isServiceApp) {
        if (handler != null) {
            try {
                return (BootErrorHandler) Class.forName(handler).newInstance();
            } catch (InstantiationException ie) {
                System.err.println("failed instantiating error handler " //$NON-NLS-1$
                        + handler);
                ie.printStackTrace();
            } catch (IllegalAccessException iae) {
                System.err.println("failed instantiating error handler " //$NON-NLS-1$
                        + handler);
                iae.printStackTrace();
            } catch (ClassNotFoundException cnfe) {
                System.err.println("failed instantiating error handler " //$NON-NLS-1$
                        + handler);
                cnfe.printStackTrace();
            }
        }
        return isServiceApp ? new BootErrorHandlerConsole()
                : (BootErrorHandler) new BootErrorHandlerGui();
    }

    /**
     * Inits the application.
     *
     * @param errorHandler the error handler
     * @param props the props
     * @param args the args
     * @return the application
     * @throws Exception the exception
     */
    private static Application initApplication(
            final BootErrorHandler errorHandler,
            final ExtendedProperties props, final String[] args)
            throws Exception {
        ApplicationInitializer appInitializer = null;
        String className = props.getProperty(PARAM_APP_INITIALIZER);
        if (className != null) {
            try {
                appInitializer = (ApplicationInitializer) Class.forName(
                        className).newInstance();
            } catch (InstantiationException ie) {
                System.err.println(
                        "failed instantiating application initializer " //$NON-NLS-1$
                        + className);
                ie.printStackTrace();
            } catch (IllegalAccessException iae) {
                System.err.println(
                        "failed instantiating application initializer " //$NON-NLS-1$
                        + className);
                iae.printStackTrace();
            } catch (ClassNotFoundException cnfe) {
                System.err.println(
                        "failed instantiating application initializer " //$NON-NLS-1$
                        + className);
                cnfe.printStackTrace();
            }
        }
        if (appInitializer == null) {
            appInitializer = new DefaultApplicationInitializer();
        }
        appInitializer.configure(props);
        Application result = appInitializer.initApplication(errorHandler, args);
        if (result == null) {
            throw new Exception(ResourceManager.getMessage(
                    Boot.PACKAGE_NAME, "bootAppInitFailed")); //$NON-NLS-1$
        }
        return result;
    }
    
    /**
     * Run shell.
     */
    private static void runShell() {
        do {
            int c;
            try {
                c = System.in.read();
            } catch (IOException ioe) {
                break;
            }
            if (('q' == (char) c) || ('Q' == (char) c)) {
                break;
            }
        } while (true);
    }
    
    /**
     * Clear boot log.
     */
    private static void clearBootLog() {
        File file = new File(BOOT_ERROR_FILE_NAME);
        if (file.isFile()) {
            file.delete();
        }
    }
    
    /**
     * Boot log.
     *
     * @param t the t
     */
    private static void bootLog(final Throwable t) {
        try {
            Writer writer = new OutputStreamWriter(
                    new FileOutputStream(BOOT_ERROR_FILE_NAME, false),
                    "UTF-8"); //$NON-NLS-1$
            try {
                writer.write("JPF Application boot failed."); //$NON-NLS-1$
                writer.write(System.getProperty("line.separator")); //$NON-NLS-1$
                writer.write(ErrorDialog.getErrorDetails(t));
            } finally {
                writer.close();
            }
        } catch (Throwable t2) {
            throw new Error("boot failed", t); //$NON-NLS-1$
        }
    }
    
    /**
     * Instantiates a new boot.
     */
    private Boot() {
        // no-op
    }
}
